package com.kylin.module.study.actions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.common.util.UTool;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.study.business.VocabularyBlogic;
import com.kylin.module.study.forms.VocabularyForm;
import com.kylin.module.study.orm.Vocabulary;
import com.kylin.module.study.orm.Vocabularyerrors;
import com.kylin.module.user.orm.User;
import com.kylin.struts.BaseDispatchAction;

/**
 * 词汇功能接口 
 * @author lzh
 *
 */
public class VocabularyAction extends BaseDispatchAction {

	protected static Logger log = Logger.getLogger(VocabularyAction.class);

	public ActionForward newList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询最新的 词汇 : ");
		String forward = "newVocabularyList";
		int size = 10;// 查询最新的 10条  
		CriteriaInfo cinfo = null;
		try {
			Locale practLocal = (Locale)request.getSession().getAttribute(Constants.CURR_PRACTLANGUAGE);
			List conditions = new ArrayList();
			// 条件： Vocabulary.language = sessionLocale(词汇所属语言 = 当前语言)
			conditions.add(new PropertyCondition("language", getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ));
			// 条件： (词汇的学习语言 = 当前学习语言)
			if(practLocal != null){
				conditions.add(new PropertyCondition("targetlang", practLocal.toString(),PropertyCondition.OPERATOR_EQ ));
			}else{
				conditions.add(new PropertyCondition("targetlang","en_GB",PropertyCondition.OPERATOR_EQ));
			}
			cinfo = new CriteriaInfo(Vocabulary.class, conditions);
			cinfo.setOrderby(Order.desc("createdon"));
			DisplayPage page = PageManager.getDisplayPage(size, 1, cinfo);
			request.setAttribute("newVocabularyList", page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}
	
	/**
	 * 业务功能入口：添加新词汇
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("开始添加新的词汇");
		String forward = "addSucc";
		VocabularyForm form = (VocabularyForm) actionForm;
		try {
			VocabularyBlogic logic = new VocabularyBlogic();
			logic.addVocabulary(form);
			request.setAttribute(Constants.MSGKEY, new MsgKey("", "添加词汇成功"));
			if(request.getParameter("nextdo").equals("list")){
				forward = "list";
				int pageSize = 10;
				int pageNum = 1;
				List conditions = new LinkedList();
				// 构造查询条件:母语
				String language = request.getParameter("language");
				if (language != null && !language.equals("")) {
					PropertyCondition cond = new PropertyCondition("language",
							language, PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				CriteriaInfo cinfo = new CriteriaInfo(Vocabulary.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
				DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
						cinfo);
				request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
			}
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	public ActionForward delete(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("删除词汇：" + id);
		try {
			VocabularyBlogic logic = new VocabularyBlogic();
			logic.deleteById(new Long(id));
			request.setAttribute(Constants.MSGKEY, new MsgKey("", "删除词汇成功"));
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}

		return this.search(mapping, actionForm, request, response);
	}
	/**
	 * 前台词汇查询
	 * 
	 * * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * */
	public ActionForward vocabularyList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("获得前台词汇");
		String forward = "list";
		String searchId = request.getParameter("searchId");
		int pageSize = 10;
		int pageNum = 1;
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List conditions = new LinkedList();
				Locale practLocal = null;
				if(request.getParameter("targetlang") != null)
				{
					request.getSession().setAttribute(Constants.CURR_PRACTLANGUAGE,UTool.getLocaleByLang(request.getParameter("targetlang")));
					practLocal = (Locale)request.getSession().getAttribute(Constants.CURR_PRACTLANGUAGE);
				}
				
				
				
				
				// 条件： Vocabulary.language = sessionLocale(词汇所属语言 = 当前语言)
				
				conditions.add(new PropertyCondition("language", getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ));
				
				// 条件： (词汇的学习语言 = 当前学习语言)
				if(practLocal != null){
					conditions.add(new PropertyCondition("targetlang", practLocal.toString(),PropertyCondition.OPERATOR_EQ ));
				}else{
					conditions.add(new PropertyCondition("targetlang","en_GB",PropertyCondition.OPERATOR_EQ));
				}
				// 构造查询条件:词汇分类
				String catvocabularyId = request.getParameter("catvocabulary");
				if (catvocabularyId != null && !catvocabularyId.equals("")) {
					Dict catvocabulary = new Dict(new Long(catvocabularyId));
					PropertyCondition cond = new PropertyCondition(
							"catvocabulary", catvocabulary,
							PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				// 构造查询条件: 词汇原形 
				String content = request.getParameter("content");
				if (content != null && !content.equals("")) {
					PropertyCondition cond = new PropertyCondition("content",
							"%" + content + "%",
							PropertyCondition.OPERATOR_LIKE);
					conditions.add(cond);
				}
				cinfo = new CriteriaInfo(Vocabulary.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}
	/**
	 * 后台词汇查询
	 * 
	 * * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * */
	public ActionForward search(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询词汇");
		String forward = "search";
		String searchId = request.getParameter("searchId");
		int pageSize = 10;
		int pageNum = 1;
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List conditions = new LinkedList();
				// 构造查询条件:母语
				String language = request.getParameter("language");
				if (language != null && !language.equals("")) {
					PropertyCondition cond = new PropertyCondition("language",
							language, PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				// 构造查询条件:学习语言
				String targetlang = request.getParameter("targetlang");
				if (targetlang != null && !targetlang.equals("")) {
					PropertyCondition cond = new PropertyCondition(
							"targetlang", targetlang,
							PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				// 构造查询条件:词汇分类
				String catvocabularyId = request.getParameter("catvocabulary");
				if (catvocabularyId != null && !catvocabularyId.equals("")) {
					Dict catvocabulary = new Dict(new Long(catvocabularyId));
					PropertyCondition cond = new PropertyCondition(
							"catvocabulary", catvocabulary,
							PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				// 构造查询条件: 词汇原形 
				String keyword_content = request.getParameter("keyword_content");
				if (keyword_content != null && !keyword_content.equals("")) {
					PropertyCondition cond = new PropertyCondition("content",
							"%" + keyword_content + "%",
							PropertyCondition.OPERATOR_LIKE);
					conditions.add(cond);
				}
				// 构造查询条件: 词汇翻译形 
				String keyword_translation = request.getParameter("keyword_translation");
				if (keyword_translation != null && !keyword_translation.equals("")) {
					PropertyCondition cond = new PropertyCondition("translation",
							"%" + keyword_translation + "%",
							PropertyCondition.OPERATOR_LIKE);
					conditions.add(cond);
				}
				cinfo = new CriteriaInfo(Vocabulary.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 根据文章ID获得需要更新的词汇
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward update(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("更新词汇" + id);
		String forward = "edit";
		Vocabulary obj = null;
		try {
			if (id != null) {
				VocabularyBlogic logic = new VocabularyBlogic();
				obj = (Vocabulary) logic.getVocabularyById(new Long(id));
			}
			request.setAttribute(Constants.KEY_REQUEST_RESULT, obj);
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 根据文章ID更新词汇
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward executeUpdate(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("更新词汇" + id);
		String forward = "list";
		VocabularyForm form = (VocabularyForm) actionForm;
		try {
			if (id != null) {
				VocabularyBlogic logic = new VocabularyBlogic();
				logic.updateVocabulary(form);
				request.setAttribute(Constants.MSGKEY, new MsgKey("",
						"修改学习词汇成功"));
			}
		} catch (Exception e) {
			doException(request, e, forward);
		}
		return this.search(mapping, actionForm, request, response);
	}
	/**
	 * 获得错误词汇信息
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward addError(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		String vocabularyId = request.getParameter("vocabularyId");
		String errorUrl = request.getParameter("errorUrl");
		request.setAttribute("errorUrl",errorUrl);
		log.debug("添加错误词汇"+vocabularyId);
		String forward = "addError";
		if(vocabularyId != null && !vocabularyId.equals(""))
		{
			try {
				Vocabulary obj = (Vocabulary)BaseHibernateDAO.findById(Vocabulary.class,new Long(vocabularyId));
				request.setAttribute(Constants.KEY_REQUEST_RESULT,obj);
			} catch (BusinessException e) {
				doException(request,e,forward);
			}
		}
		return mapping.findForward(forward);
	}
	/**
	 * 保存错误词汇信息
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward saveError(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)
	{
		log.debug("存储错误词汇信息"+request.getParameter("description"));
		String forward = "addError";
		String vocabularyId = request.getParameter("vocabularyId");
		String description = request.getParameter("description");
		User user = (User)request.getSession().getAttribute(Constants.CURR_USER);		
		try
		{
			Vocabulary vocabulary = (Vocabulary)BaseHibernateDAO.findById(Vocabulary.class,new Long(vocabularyId));
			VocabularyBlogic logic = new VocabularyBlogic();
			logic.addVocabularyError(user, vocabulary, description);
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
	/**
	 * 删除错误词汇信息
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward deleteError(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.debug("删除词汇：" + id);
		try {
			VocabularyBlogic logic = new VocabularyBlogic();
			logic.deleteErrorById(new Long(id));
			request.setAttribute(Constants.MSGKEY, new MsgKey("", "删除成功"));
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return this.searchError(mapping, actionForm, request, response);
	}
	/**
	 * 查询错误词汇信息
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward searchError(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("查询词汇报错列表");
		String forward = "listError";
		String searchId = request.getParameter("searchId");
		int pageSize = 10;
		int pageNum = 1;
		CriteriaInfo cinfo = null;
		try
		{
			if(request.getParameter("page") != null)
			{
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if(searchId == null)
			{
				List conditions = new LinkedList();
				//构造查询条件:母语
				String language = request.getParameter("language");
				if(language != null && !language.equals(""))
				{
					PropertyCondition cond = new PropertyCondition("language",language,PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}

				// 构造查询条件: 词汇
				String keyword_content = request.getParameter("keyword_content");
				if (keyword_content != null && !keyword_content.equals("")) {
					Vocabulary content = new Vocabulary(new Long(keyword_content));
					PropertyCondition cond = new PropertyCondition("vocabulary",
							content,
							PropertyCondition.OPERATOR_EQ);
					conditions.add(cond);
				}
				
				cinfo = new CriteriaInfo(Vocabularyerrors.class, conditions);
				cinfo.setOrderby(Order.desc("createdon"));
				addUserCacheCriteriaInfo(request, cinfo);
			} else {
				cinfo = getUserCacheCriteriaInfo(request, searchId);
			}
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum,
					cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
}